package com.stupidzhe.jdklearning.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by Mr.W on 2017/11/10.
 */
public class BufferTestClass {

    private static final String content = "hello\nworld";

    public static void main(String[] args) {

        try {
            FileChannel
                    outputChannel = new FileOutputStream("./src/com/stupidzhe/jdklearning/io/file-test/file5.c").getChannel(),
                    inputChannel = new FileInputStream("./src/com/stupidzhe/jdklearning/io/file-test/file5.c").getChannel();
            ByteBuffer bb = ByteBuffer.allocate(content.length() * 2);
            bb.put(content.getBytes());
            bb.put(content.getBytes());
            bb.flip();
            //
            outputChannel.force(true);
            while (bb.hasRemaining()) {
                outputChannel.write(bb);
            }
            outputChannel.close();

            bb = ByteBuffer.allocate(content.length() * 2 - 5);
            bb.clear();
            while (inputChannel.read(bb) != -1) {
                bb.flip(); // prepare for writing
                while (bb.hasRemaining()) {
                    System.out.print((char) bb.get());
                }
                // 如果我们打算使用缓冲器执行进一步的read()操作
                // 我们必须调用clear()来为每个read()做好准备
                bb.clear(); // prepare for reading
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
